<!-- Bot Read Me -->
<!-- Author: Edwin -->
<template>
  <el-dialog :close-on-click-modal="false"
             :close-on-press-escape="false"
             width="951px"
             :visible.sync="visible"
             :before-close="beforeCloseDialog">
    <div class='bot-read-me'>
      <el-card shadow="never">
        <div class="bot-read-me-content">
          <el-form :model="dataForm"
                   ref="dataForm"
                   :rules="dataFormRules"
                   :inline="false"
                   v-loading="loading"
                   label-width="140px">
            <el-tabs v-model="activeTab">
              <el-tab-pane :label="$t('custom.botStore.info')"
                           name="0">
                <el-form-item :label="$t('custom.botStore.scriptName')"
                              prop="name">
                  <el-input v-model="dataForm.name"></el-input>
                </el-form-item>
                <!-- <el-form-item :label="$t('custom.botStore.icon')">
                  <el-input v-model="dataForm.icon"></el-input>
                </el-form-item> -->
                <el-form-item :label="$t('custom.botStore.icon')"
                              prop="icon">
                  <el-select v-model="dataForm.icon"
                             clearable
                             style="width: 80%;">
                    <el-option v-for="its in iconList"
                               :key="its.dictValue"
                               :label="its.dictLabel"
                               :value="its.dictValue"></el-option>
                  </el-select>
                  <el-avatar v-if="dataForm.icon"
                             size="small"
                             :src="dataForm.icon"
                             style="vertical-align: middle;margin-left: 10px;"></el-avatar>
                </el-form-item>
                <!-- <el-form-item :label="$t('custom.botStore.system')"
                              prop="scope">
                  <el-select v-model="dataForm.scope"
                             :placeholder="$t('custom.botStore.system')"
                             style="width: 100%;">
                    <el-option v-for="its in scopeList"
                               :key="its.dictValue"
                               :label="its.dictLabel"
                               :value="its.dictValue"></el-option>
                  </el-select>
                </el-form-item> -->
                <el-form-item prop="type"
                              :label="$t('custom.botStore.type')">
                  <el-select v-model="dataForm.type"
                             :placeholder="$t('custom.botStore.type')"
                             style="width: 100%;">
                    <el-option v-for="its in typeList"
                               :key="its.dictValue"
                               :label="its.dictLabel"
                               :value="its.dictValue"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="triggerEvent"
                              :label="$t('custom.botStore.triggerEvent')">
                  <el-select v-model="dataForm.triggerEvent"
                            :disabled="!!dataForm.id"
                             :placeholder="$t('custom.botStore.triggerEvent')"
                             style="width: 100%;">
                    <el-option v-for="its in triggerEventList"
                               :key="its.dictValue"
                               :label="its.dictLabel"
                               :value="its.dictValue"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :label="$t('custom.botStore.briefDescription')"
                              prop="briefDescription">
                  <el-input type="textarea"
                            :rows="4"
                            v-model="dataForm.briefDescription"></el-input>
                </el-form-item>
                <el-form-item :label="$t('custom.botStore.detailedDescription')"
                              prop="description">
                  <el-input type="textarea"
                            :rows="4"
                            v-model="dataForm.description"></el-input>
                </el-form-item>
                <el-form-item :label="$t('user.roleIdList')"
                              prop="roleIds">
                  <el-select v-model="dataForm.roleIds"
                             multiple
                             style="width: 100%;">
                    <el-option v-for="(role,index) in fullRoleList"
                               :key="index"
                               :label="role.name"
                               :value="role.roleId"></el-option>
                  </el-select>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane v-if="isHasBlockManagementPermission" :label="$t('custom.botStore.logic')"
                           name="1">
                <codemirror ref="codemirror-logic"
                            :options="cmOptions"
                            @changes="logicDataChange"></codemirror>
              </el-tab-pane>
              <el-tab-pane v-if="isHasBlockManagementPermission" :label="$t('custom.botStore.para')"
                           name="2">
                <v-jsoneditor v-model="dataForm.paramsJson"
                              :options="jsoneditorSetting.options"
                              :plus="jsoneditorSetting.plus"
                              :height="jsoneditorSetting.height"
                              :indentation="jsoneditorSetting.indentation"
                              :search="jsoneditorSetting.search"
                              :path="jsoneditorSetting.path"
                              :color="jsoneditorSetting.color"
                              @error="onError"></v-jsoneditor>
              </el-tab-pane>
              <el-tab-pane v-if="isHasBlockManagementPermission" :label="$t('custom.botStore.preview')"
                           name="3">
                <el-alert :title="$t('custom.botStore.previewTips')"
                          type="warning"></el-alert>
                <ScriptRender ref="script-render"
                              :dataForm='previewDataForm'
                              :showJson='showJson' />
              </el-tab-pane>
            </el-tabs>
          </el-form>
        </div>
      </el-card>
    </div>
    <template slot="footer">
      <el-button size="small" :disabled="loading"
                 @click="canceldialog">{{ $t('cancel') }}</el-button>
      <el-button size="small"
                 type="primary" :disabled="loading"
                 @click="dataFormSubmitHandle(false)">{{ $t('custom.botStore.save') }}</el-button>
    </template>
  </el-dialog>
</template>
<script>
import { debounce } from 'lodash'
import { codemirror } from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/cobalt.css'
import 'codemirror/mode/groovy/groovy.js'
import ScriptRender from '@/components/script-render/index'

export default {
  components: {
    codemirror, ScriptRender
  },
  data () {
    return {
      loading: false,
      visible: false,
      dataForm: {
        id: null,
        name: null,
        context: null,
        scope: 'System',
        triggerEvent: null,
        paramsJson: null,
        description: null,
        briefDescription: null,
        type: null,
        icon: null,
        roleIds: []
      },
      fullRoleList: [],
      cmOptions: {
        tabSize: 4,
        theme: 'cobalt',
        lineNumbers: true,
        line: true,
        mode: 'text/x-groovy',
        smartIndent: true,
        lineWrapping: true,
        foldGutter: true,
        matchBrackets: true,
        autoCloseBrackets: true,
        autoRefresh: true,
        autofocus: true
        // readOnly: 'nocursor'
      },
      jsoneditorSetting: {
        options: { mode: 'tree', modes: ['tree', 'code'] },
        plus: false,
        height: '400px',
        indentation: 2,
        search: true,
        color: 'red',
        path: false
      },
      activeTab: '0',
      dataFormRules: {
        name: [],
        scope: [],
        type: [],
        triggerEvent: [],
        description: []
      },
      previewDataForm: {}
    }
  },
  computed: {
    iconList () {
      return  [] //window.SITE_CONFIG['dictList'].find(e => e.dictType === 'icon_list').dataList
    },
    typeList () {
      return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'script_type').dataList
    },
    scopeList () {
      return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'Script_scope').dataList
    },
    triggerEventList () {
      return window.SITE_CONFIG['dictList'].find(e => e.dictType === 'script_triggerEvent').dataList
    },
    showJson () {
      try {
        return this.dataForm.paramsJson.fields
      } catch (error) {
        return null
      }
    },
    isHasBlockManagementPermission() {
      return this.$hasPermission('sys:bots:block:management')
    }
  },
  watch: {
    activeTab (val) {
      if (val === '1') {
        this.setCodemirrorValue()
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.activeTab = '0'
      this.$nextTick(async () => {
        this.dataForm.paramsJson = null
        this.loading = true
        if (this.dataForm.id) {
          await this.getInfo()
        }
        this.getRoleList()
      })
    },
    logicDataChange: debounce(function (e) {
      try {
        this.dataForm.context = e.getValue()
      } catch (error) {
      }
    }, 800),
    getInfo () {
      return new Promise(resolve => {
        let _self = this
        const params = {
          id: _self.dataForm.id
        }
        _self.$interface.sysScript.getSysScriptInfoApi(params)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return _self.$message.error(res.msg)
            }
            _self.dataForm = Object.assign({}, _self._.merge(_self.dataForm, res.data))
            resolve()
          }).catch(() => { })
      })
    },
    onError (value) {
    },
    dataFormSubmitHandle (isVisible) {
      this.loading = true
      this.dataForm.language = 'Groovy'
      const params = {
        ...this.dataForm
      }
      const changeScriptInfo = () => {
        if (!this.dataForm.id) {
          return this.$interface.sysScript.saveSysScriptInfoApi(params)
        } else {
          return this.$interface.sysScript.updateSysScriptInfoApi(params)
        }
      }
      changeScriptInfo().then(({ data: res }) => {
        this.loading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.$message.success(res.msg)
        this.$emit('refreshDataList')
        this.visible = isVisible
      }).catch(() => { this.loading = false})
    },
    setCodemirrorValue () {
      if (this.activeTab === '0') {
        return false
      }
      setTimeout(() => {
        try {
          const context = this.dataForm.context || ''
          this.activeTab === '1' && this.$refs[`codemirror-logic`].codemirror.setValue(context)
        } catch (error) {
        }
      }, 300)
    },
    canceldialog () {
      this.visible = false
      this.beforeCloseDialog()
      // this.$emit('refreshDataList')
    },
    beforeCloseDialog () {
      Object.assign(this.$data, this.$options.data())
    },
    getRoleList () {
      try {
        const params = {
          tenantCode: this.$store.state.user.tenantCode
        }
        this.$interface.system.getClientRoleListApi(params)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.fullRoleList = res.data
            this.loading = false
          }).catch(() => { })
      } catch (error) {
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import "src/views/modules/mspbots/bots/my-bots/my-bot";
</style>
